package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class AddressBookServiceImpl implements AddressBookService {



    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 添加地址
     * @param addressBook
     */
    @Override
    public void addAddressBook(AddressBook addressBook) {
        addressBookMapper.insertAddressBook(addressBook);
    }


    /**
     * 查询所有的地址信息
     * @return
     */
    @Override
    public List<AddressBook> selectAllAddressBook(AddressBook addressBook) {
        List<AddressBook> addressBookList = addressBookMapper.selectAllAddressBook(addressBook);
        return addressBookList;
    }


    /**
     * 查询默认地址
     * @param currentId
     * @return
     */
    @Override
    public AddressBook selectIsDefault(Long currentId) {
        AddressBook addressBook = addressBookMapper.selectIsDefault(currentId);
        return addressBook;
    }


    /**
     * 通过ID查询地址信息
     * @param id
     * @return
     */
    @Override
    public AddressBook selectAddressBookById(Long id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return addressBook;
    }


    /**
     * 根据ID修改地址
     * @param addressBook
     */
    @Override
    public void modifyAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.modifyAddressBook(addressBook);
    }


    /**
     * 根据ID删除地址
     * @param id
     */
    @Override
    public void deleteAddressBook(Long id) {
        addressBookMapper.deleteAddressBook(id);
    }


    /**
     * 设置默认地址
     * @param addressBook
     */
    @Transactional
    @Override
    public void setDefault(AddressBook addressBook) {
        // 将用户下的所有地址改为非默认地址
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.modifyAllDefault(addressBook);

        // 将选中的修改为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.modifyAddressBook(addressBook);
    }
}
